/*
 * @Descripttion:
 * @version:
 * @Author: ZmSama
 * @Date: 2022-01-11 09:42:37
 */
import { useEffect, useRef, useState } from "react";
import "../../mock/api";
import "./css/index.css";
import "./css/iconfont.css";
import dateGenerator from "./utils";
import { FixedSizeList } from "react-window";
import ReactTooltip from "react-tooltip";
type ColumnsType = {
  date: string;
  week: string;
};
type TagsProps = {
  id: string;
  offset: number;
  width: number;
  orderNum: number;
  color: string;
};

type DataSourceProps = {
  id: string;
  title: string;
  orderNum: number;
  toggle: boolean;
  isLeaf: boolean;
  tags: TagsProps[];
  children?: DataSourceProps[];
};
type GanttTableProps = {
  time: string;
  dataSource: DataSourceProps[];
  height: number;
  itemHeight: number;
};
export default function GanttTable(props: GanttTableProps) {
  const { dataSource, time, height = 616, itemHeight = 41 } = props;
  const [columns, setColumns] = useState<ColumnsType[]>([]);
  const [tableData, setTableData] = useState<DataSourceProps[]>([]);
  const FixedSizeListRef = useRef<any>(null);
  const MainFixedSizeListRef = useRef<any>(null);
  const HeaderScrollRef = useRef<any>(null);
  const MainScrollRef = useRef<any>(null);
  const [enterMain, setEnterMain] = useState(false);
  const [enterHeader, setEnterHeader] = useState(false);

  const [position, setPosition] = useState<{
    x: number;
    y: number;
  }>({
    x: 0,
    y: 0,
  });
  const [toolTipsData, setToolTipsData] = useState<any>(null);
  const toopTipRef = useRef<any>(null);

  // 鼠标在色条行移动时
  const mouseMoveHandle = (val: any, e: any) => {
    // console.log(val);
    setToolTipsData(val);
    setPosition({
      x: e.clientX - 60,
      y: e.clientY,
    });
    ReactTooltip.show(toopTipRef.current);
  };

  // 鼠标离开色条
  const mouseLeaveHandle = () => {
    ReactTooltip.hide(toopTipRef.current);
  };

  // 动态改变tooltips的位置
  const computedPosition = () => {
    return { left: position.x, top: position.y };
  };

  // 点击树节点的展开或收缩
  const toggleTreeNode = (id: string) => {
    tableData.forEach((item, index) => {
      if (item.id === id) {
        if (item.toggle) {
          item.toggle = false;
          if (item.children) {
            let result = item.children;
            // 如果是打开那么这里就去除上次添加的子节点
            tableData.splice(index + 1, result.length);
          }
        } else {
          item.toggle = true;
          if (item.children) {
            // 反之追加子节点
            let result = item.children;
            tableData.splice(index + 1, 0, ...result);
          }
        }
        setTableData([...tableData]);
      }
    });
  };

  // 鼠标进入头部时
  const enterHeaderHandle = () => {
    setEnterHeader(true);
    setEnterMain(false);
  };
  // 鼠标进入中间时
  const enterMainHandle = () => {
    setEnterHeader(false);
    setEnterMain(true);
  };

  // 中间行生成方法
  const MainRow = (props: any) => {
    const style = props.style;
    const item = props.data[props.index];
    const customerSty = {
      ...style,
      width: columns.length * 120 + "px",
      overflowY: "auto",
      overflowX: "hidden",
    };
    return (
      <div style={customerSty}>
        <div className="main-row">
          {item.tags.map((row: any) => {
            return (
              <div
                onMouseMove={(e) => mouseMoveHandle(row, e)}
                onMouseLeave={mouseLeaveHandle}
                key={row.id}
                style={{
                  position: "absolute",
                  top: "50%",
                  transform: "translateY(-50%)",
                  width: row.width * 120 + "px",
                  left: row.offset * 120 + "px",
                  backgroundColor: row.color,
                  height: "16px",
                  borderRadius: "16px",
                }}
              />
            );
          })}
        </div>
      </div>
    );
  };
  // 左边行生成方法
  const LeftRow = (props: any) => {
    const style = props.style;
    const item = props.data[props.index];
    return (
      <div
        style={style}
        className={!item.children ? "left-item isLeaf" : "left-item"}
        key={item.id}
      >
        <div className="option" onClick={() => toggleTreeNode(item.id)}>
          {item.children ? (
            item.toggle ? (
              <i className="iconfont icon-minus-rectangle" />
            ) : (
              <i className="iconfont icon-add-rectangle" />
            )
          ) : null}
        </div>
        <div className="icon">
          {item.children ? (
            item.toggle ? (
              <i className="iconfont icon-folder" />
            ) : (
              <i className="iconfont icon-folder-add" />
            )
          ) : (
            <i className="iconfont icon-file" />
          )}
        </div>
        <div className="title">{item.title}</div>
        <div className="num">{item.orderNum}</div>
      </div>
    );
  };

  // 滚动左边的虚拟容器时
  const leftScrollHandle = ({ scrollOffset }: { scrollOffset: number }) => {
    MainFixedSizeListRef.current?.scrollTo(scrollOffset);
  };
  // 滚动中间的虚拟容器时
  const mainScrollHandle = ({ scrollOffset }: { scrollOffset: number }) => {
    console.log(scrollOffset);
    FixedSizeListRef.current?.scrollTo(scrollOffset);
  };

  // 横向滚动中间时
  const mainWrapScrollHandle = (e: any) => {
    // console.log(e);
    if (enterMain) {
      HeaderScrollRef.current!.scrollLeft = e.target!.scrollLeft;
    }
  };

  // 横向滚动表头时
  const headerScrollHandle = (e: any) => {
    if (enterHeader) {
      MainScrollRef.current!.scrollLeft = e.target!.scrollLeft;
    }
  };
  const toolTipHtml = () => {
    return `<div>
      <div class="title">${toolTipsData?.id}</div>
      <p>订单数量：${toolTipsData?.orderNum}</p>
      <div style="background:${toolTipsData?.color};width:30px;height:30px;border-radius:50%"></div>
    </div>`;
  };

  useEffect(() => {
    let data = dateGenerator(new Date(time));
    setColumns(data);
  }, []);

  useEffect(() => {
    setTableData(dataSource);
  }, [dataSource]);
  return (
    <div className="gantt-table-wrap">
      {/* 固定头部 */}
      <div
        className="table-header-wrap"
        onScroll={headerScrollHandle}
        ref={HeaderScrollRef}
        onMouseEnter={enterHeaderHandle}
      >
        {columns.map((item) => {
          return (
            <div
              className="header-item"
              key={item.date}
            >{`${item.date}${item.week}`}</div>
          );
        })}
      </div>
      {/* 固定左侧 */}
      <div className="table-left-wrap">
        <div className="left-scroll-wrap">
          <div className="left-first-tag">
            <span>跟单号</span>
          </div>
          <FixedSizeList
            ref={FixedSizeListRef}
            height={height}
            itemCount={tableData.length}
            itemSize={itemHeight}
            width="100%"
            itemData={tableData}
            onScroll={leftScrollHandle}
          >
            {LeftRow}
          </FixedSizeList>
        </div>
      </div>
      {/* 中间固定表格 */}
      <div
        className="table-main-wrap"
        onScroll={mainWrapScrollHandle}
        ref={MainScrollRef}
        onMouseEnter={enterMainHandle}
      >
        <FixedSizeList
          ref={MainFixedSizeListRef}
          height={height}
          itemCount={tableData.length}
          itemSize={itemHeight}
          width={columns.length * 120 + "px"}
          itemData={tableData}
          onScroll={mainScrollHandle}
        >
          {MainRow}
        </FixedSizeList>
      </div>

      <div
        ref={toopTipRef}
        data-tip={toolTipHtml()}
        data-place="bottom"
        data-html={true}
        data-class="myTips"
      ></div>
      <ReactTooltip overridePosition={computedPosition} />
    </div>
  );
}
